﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using OilDB;


namespace MainApp
{
    public partial class FrmInputSells : XtraForm
    {
        private OilDB.DataServices data;
        private Dictionary<Guid, SpinEdit> productsSpinCalc = new Dictionary<Guid, SpinEdit>();
        private Dictionary<Guid, SpinEdit> productsSpinReal = new Dictionary<Guid, SpinEdit>();
        private Guid currentStore;
        private bool missClick;

        public FrmInputSells(OilDB.DataServices data, Guid store)
        {
            InitializeComponent();

            bdsCustomers.DataSource = data.DsOil;
            bdsProducts.DataSource = data.DsOil;
            bdsStores.DataSource = data.DsOil;
            this.data = data;
            currentStore = store;            
        }
        //checked
        private void FrmInputSells_Load(object sender, EventArgs e)
        {
            LoadGroupProducts();

            if (currentStore != Guid.Empty)
                InitControlProperties();
        }
        //checked
        private void gridViewInputSells_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
            DataRow row = view.GetDataRow(e.RowHandle);

            row["ID"] = Guid.NewGuid();
            row["StoreID"] = currentStore;
            row["SellTime"] = DateTime.Now;
            row["Customer"] = Guid.Empty;
        }
        //checked
        private void cboStores_EditValueChanged(object sender, EventArgs e)
        {
            gridInputSells.Enabled = true;
            groupControlProducts.Enabled = true;
            btnCancel.Enabled = true;
            btnOK.Enabled = true;
            
            currentStore = (Guid)cboStores.EditValue;

            foreach (Guid productId in productsSpinCalc.Keys)
            {
                SpinEdit spin = productsSpinCalc[productId];
                spin.EditValue = GetTotalExport(currentStore, productId);
                spin = productsSpinReal[productId];
                spin.Properties.MaxValue = GetTotalImport(currentStore, productId);
            }
            dataSetOilManagement.Sells.Clear();
        }
        //checked
        private void gridViewInputSells_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            if (missClick)
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                return;
            }
            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;

            if (XtraMessageBox.Show(e.ErrorText + "\nBạn có muốn sửa lại không?\n Bấm Yes để sửa lại.\n Bấm No để bỏ qua.", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Error) == System.Windows.Forms.DialogResult.No)
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
                view.CancelUpdateCurrentRow();
            }
        }
        //checked
        private void gridViewInputSells_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
            view.ClearColumnErrors();
            DevExpress.XtraGrid.Columns.GridColumn column;
            column = view.Columns["Product"];
            if (view.GetRowCellValue(e.RowHandle, column) is DBNull)
            {
                e.Valid = false;
                view.SetColumnError(column, "Chưa chọn loại sản phẩm");
            }
            column = view.Columns["Amount"];
            if (view.GetRowCellValue(e.RowHandle, column) is DBNull)
            {
                e.Valid = false;
                view.SetColumnError(column, "Chưa nhập số lượng");
            }
            column = view.Columns["Paid"];
            if (view.GetRowCellValue(e.RowHandle, column) is DBNull)
            {
                e.Valid = false;
                view.SetColumnError(column, "Chưa nhập số tiền đã trả");
            }

            e.ErrorText = "Dữ liệu nhập có lỗi";
            if (e.Valid)
            {
                DataRow row = view.GetDataRow(e.RowHandle);
                
                //if ((decimal)view.GetRowCellValue(e.RowHandle, "Paid") > (decimal)view.GetRowCellValue(e.RowHandle, "Total"))
                //{
                //    e.Valid = false;
                //    e.ErrorText = "Không thể trả nhiều hơn tổng tiền";
                //    return;
                //}

                
                if (!ValidateRetail(row))
                {
                    e.Valid = false;
                    view.SetColumnError(view.Columns["Paid"], "Bán lẻ thì phải trả đủ tiền");
                    return;
                }

                decimal tt1, tt2;
                if (view.IsNewItemRow(e.RowHandle))
                {
                    tt1 = 0;
                    tt2 = (decimal)row["Amount"];
                    Guid productId = (Guid)row["Product"];
                    decimal tt3 = (decimal)productsSpinCalc[productId].EditValue;
                    decimal max = productsSpinReal[productId].Properties.MaxValue;
                    if ((tt3 + tt2) > max)
                    {
                        e.Valid = false;
                        e.ErrorText = "Không thể bán nhiều hơn nhập. Tổng nhập: " + max;
                    }
                    else
                    {
                        productsSpinCalc[productId].EditValue = tt3 + tt2;
                    }
                }
                else if (!view.IsFilterRow(e.RowHandle))
                {
                    try //error when no data is proposed
                    {
                        tt1 = (decimal)row["Amount", DataRowVersion.Current];
                        tt2 = (decimal)row["Amount", DataRowVersion.Proposed];
                        Guid productIdOld = (Guid)row["Product", DataRowVersion.Current];
                        Guid productIdNew = (Guid)row["Product", DataRowVersion.Proposed];
                        productsSpinCalc[productIdOld].EditValue = (decimal)productsSpinCalc[productIdOld].EditValue - tt1;

                        decimal tt3 = (decimal)productsSpinCalc[productIdNew].EditValue;
                        decimal max = productsSpinReal[productIdNew].Properties.MaxValue;
                        if ((tt3 + tt2) > max)
                        {
                            e.Valid = false;
                            e.ErrorText = "Không thể bán nhiều hơn nhập. Tổng nhập: " + max;
                            productsSpinCalc[productIdOld].EditValue = (decimal)productsSpinCalc[productIdOld].EditValue + tt1;
                        }
                        else
                        {
                            productsSpinCalc[productIdNew].EditValue = tt3 + tt2;                          
                        }
                    }
                    catch (Exception)
                    {

                        //throw;
                    }
                }

            }
        }
        //checked
        private void gridViewInputSells_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
                if (view.FocusedRowHandle < 0)
                    return;

                if (XtraMessageBox.Show("Xóa những dòng đang chọn ?", "Xác nhận", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != DialogResult.Yes)
                    return;
                int[] index = view.GetSelectedRows();

                for (int i = 0; i < index.Length; i++)
                {
                    DataRow row = view.GetDataRow(index[i]);
                    decimal tmp = (decimal)row["Amount"];
                    decimal tmp2 = (decimal)productsSpinCalc[(Guid)row["Product"]].EditValue;
                    productsSpinCalc[(Guid)row["Product"]].EditValue = tmp2 - tmp;
                }

                view.DeleteSelectedRows();
            }
        }
        //checked
        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }
        //checked
        private void btnOK_Click(object sender, EventArgs e)
        {
            foreach (DataSetOilManagement.SellsRow row in dataSetOilManagement.Sells.Rows)
            {
                DataSetOilManagement.SellsRow newRow = data.DsOil.Sells.NewSellsRow();
                CopyASell(row, newRow);
                data.DsOil.Sells.AddSellsRow(newRow);
                CalcDebt(newRow);
            }
            foreach (Guid productId in productsSpinCalc.Keys)
            {
                decimal tt1 = (decimal)productsSpinCalc[productId].EditValue;
                decimal tt2 = (decimal)productsSpinReal[productId].EditValue;
                if (tt1 < tt2)
                {
                    DataSetOilManagement.SellsRow newRow = data.DsOil.Sells.NewSellsRow();
                    newRow.ID = Guid.NewGuid();
                    newRow.Product = productId;
                    newRow.StoreID = (Guid)cboStores.EditValue;
                    newRow.SellTime = DateTime.Now;
                    newRow.Amount = tt2 - tt1;
                    DataSetOilManagement.ProductsRow tmp = data.DsOil.Products.FindByID(productId);
                    newRow.Price = tmp.Price;
                    newRow.Commission = tmp.Commission;
                    newRow.Paid = newRow.Price * newRow.Amount;
                    newRow.Note = "Bán lẻ";
                    newRow.Customer = Guid.Empty;
                    data.DsOil.Sells.AddSellsRow(newRow);
                }
                DataSetOilManagement.ExportStatisticsAllRow temp = data.DsOil.ExportStatisticsAll.FindByProductStoreID(productId, (Guid)cboStores.EditValue);
                if (temp != null)
                    temp.TotalAmount = tt2;
                else if (tt2 != 0)
                {
                    data.DsOil.ExportStatisticsAll.AddExportStatisticsAllRow((Guid)cboStores.EditValue, productId, tt2);
                }
            }
            DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }
        //checked
        private void gridViewInputSells_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            missClick = false;
            DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
            if (e.Column.FieldName == "Product")
            {
                DataSetOilManagement.ProductsRow tmp = data.DsOil.Products.FindByID((Guid)e.Value); 
                DataSetOilManagement.SellsRow row = (DataSetOilManagement.SellsRow)view.GetDataRow(e.RowHandle);
                row.Price = tmp.Price;
                row.Commission = tmp.Commission;
                
            }
            if (view.IsNewItemRow(e.RowHandle) && !(view.GetRowCellValue(e.RowHandle, "Amount") is DBNull) && !(view.GetRowCellValue(e.RowHandle, "Price") is DBNull))
            {
                DataSetOilManagement.SellsRow row = (DataSetOilManagement.SellsRow)view.GetDataRow(e.RowHandle);
                row.Total = row.Amount * row.Price;
            }
        }
        //checked
        private void gridViewInputSells_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
            if (view.IsNewItemRow(e.FocusedRowHandle))
            {
                missClick = true;
                view.AddNewRow();
            }
        }
    }
}